<template>
  <div class="tenant-config">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 系统配置 -->
      <el-tab-pane label="系统配置" name="system">
        <div class="config-section">
          <el-form :model="systemConfig" label-width="150px">
            <el-form-item label="系统主题">
              <el-select v-model="systemConfig.theme" placeholder="请选择主题">
                <el-option label="默认主题" value="default" />
                <el-option label="蓝色主题" value="blue" />
                <el-option label="绿色主题" value="green" />
                <el-option label="红色主题" value="red" />
              </el-select>
            </el-form-item>
            <el-form-item label="系统语言">
              <el-select v-model="systemConfig.language" placeholder="请选择语言">
                <el-option label="简体中文" value="zh-CN" />
                <el-option label="English" value="en-US" />
                <el-option label="繁體中文" value="zh-TW" />
              </el-select>
            </el-form-item>
            <el-form-item label="时区设置">
              <el-select v-model="systemConfig.timezone" placeholder="请选择时区">
                <el-option label="北京时间 (UTC+8)" value="Asia/Shanghai" />
                <el-option label="东京时间 (UTC+9)" value="Asia/Tokyo" />
                <el-option label="纽约时间 (UTC-5)" value="America/New_York" />
                <el-option label="伦敦时间 (UTC+0)" value="Europe/London" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 功能配置 -->
      <el-tab-pane label="功能配置" name="feature">
        <div class="config-section">
          <el-form :model="featureConfig" label-width="150px">
            <el-form-item label="文件上传">
              <el-switch v-model="featureConfig.fileUpload" />
              <span class="config-desc">允许用户上传文件</span>
            </el-form-item>
            <el-form-item label="在线聊天">
              <el-switch v-model="featureConfig.onlineChat" />
              <span class="config-desc">启用在线聊天功能</span>
            </el-form-item>
            <el-form-item label="视频通话">
              <el-switch v-model="featureConfig.videoCall" />
              <span class="config-desc">启用视频通话功能</span>
            </el-form-item>
            <el-form-item label="屏幕共享">
              <el-switch v-model="featureConfig.screenShare" />
              <span class="config-desc">启用屏幕共享功能</span>
            </el-form-item>
            <el-form-item label="AI助手">
              <el-switch v-model="featureConfig.aiAssistant" />
              <span class="config-desc">启用AI助手功能</span>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 限制配置 -->
      <el-tab-pane label="限制配置" name="limit">
        <div class="config-section">
          <el-form :model="limitConfig" label-width="150px">
            <el-form-item label="最大文件大小">
              <el-input-number 
                v-model="limitConfig.maxFileSize" 
                :min="1" 
                :max="1000" 
                :step="1"
                style="width: 200px"
              />
              <span class="config-unit">MB</span>
              <span class="config-desc">单个文件最大上传大小</span>
            </el-form-item>
            <el-form-item label="用户存储配额">
              <el-input-number 
                v-model="limitConfig.storageQuotaPerUser" 
                :min="100" 
                :max="10000" 
                :step="100"
                style="width: 200px"
              />
              <span class="config-unit">MB</span>
              <span class="config-desc">每个用户的存储配额</span>
            </el-form-item>
            <el-form-item label="最大并发会话">
              <el-input-number 
                v-model="limitConfig.maxConcurrentSessions" 
                :min="1" 
                :max="100" 
                :step="1"
                style="width: 200px"
              />
              <span class="config-unit">个</span>
              <span class="config-desc">用户最大同时在线会话数</span>
            </el-form-item>
            <el-form-item label="API调用频率">
              <el-input-number 
                v-model="limitConfig.apiRateLimit" 
                :min="10" 
                :max="10000" 
                :step="10"
                style="width: 200px"
              />
              <span class="config-unit">次/分钟</span>
              <span class="config-desc">API调用频率限制</span>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 安全配置 -->
      <el-tab-pane label="安全配置" name="security">
        <div class="config-section">
          <el-form :model="securityConfig" label-width="150px">
            <el-form-item label="密码最小长度">
              <el-input-number 
                v-model="securityConfig.passwordMinLength" 
                :min="6" 
                :max="20" 
                :step="1"
                style="width: 200px"
              />
              <span class="config-unit">位</span>
            </el-form-item>
            <el-form-item label="密码复杂度">
              <el-switch v-model="securityConfig.passwordComplexity" />
              <span class="config-desc">要求密码包含大小写字母、数字和特殊字符</span>
            </el-form-item>
            <el-form-item label="会话超时">
              <el-input-number 
                v-model="securityConfig.sessionTimeout" 
                :min="5" 
                :max="480" 
                :step="5"
                style="width: 200px"
              />
              <span class="config-unit">分钟</span>
              <span class="config-desc">用户无操作自动退出时间</span>
            </el-form-item>
            <el-form-item label="登录失败限制">
              <el-input-number 
                v-model="securityConfig.maxLoginAttempts" 
                :min="3" 
                :max="10" 
                :step="1"
                style="width: 200px"
              />
              <span class="config-unit">次</span>
              <span class="config-desc">连续登录失败后锁定账户</span>
            </el-form-item>
            <el-form-item label="双因子认证">
              <el-switch v-model="securityConfig.twoFactorAuth" />
              <span class="config-desc">启用双因子认证</span>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 通知配置 -->
      <el-tab-pane label="通知配置" name="notification">
        <div class="config-section">
          <el-form :model="notificationConfig" label-width="150px">
            <el-form-item label="邮件通知">
              <el-switch v-model="notificationConfig.emailEnabled" />
              <span class="config-desc">启用邮件通知</span>
            </el-form-item>
            <el-form-item label="短信通知">
              <el-switch v-model="notificationConfig.smsEnabled" />
              <span class="config-desc">启用短信通知</span>
            </el-form-item>
            <el-form-item label="推送通知">
              <el-switch v-model="notificationConfig.pushEnabled" />
              <span class="config-desc">启用浏览器推送通知</span>
            </el-form-item>
            <el-form-item label="系统公告">
              <el-switch v-model="notificationConfig.systemAnnouncement" />
              <span class="config-desc">显示系统公告</span>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <!-- 自定义配置 -->
      <el-tab-pane label="自定义配置" name="custom">
        <div class="config-section">
          <div class="custom-config-header">
            <el-button type="primary" icon="Plus" @click="handleAddConfig">添加配置</el-button>
            <el-button type="success" icon="Upload" @click="handleImportConfig">导入配置</el-button>
            <el-button type="warning" icon="Download" @click="handleExportConfig">导出配置</el-button>
          </div>
          
          <el-table :data="customConfigs" v-loading="customLoading">
            <el-table-column label="配置键" prop="configKey" width="200" />
            <el-table-column label="配置值" prop="configValue" :show-overflow-tooltip="true" />
            <el-table-column label="配置类型" prop="configType" width="100">
              <template #default="scope">
                <el-tag :type="getConfigTypeTag(scope.row.configType)">
                  {{ scope.row.configType }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="描述" prop="description" :show-overflow-tooltip="true" />
            <el-table-column label="系统配置" prop="isSystem" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isSystem ? 'danger' : 'success'">
                  {{ scope.row.isSystem ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleEditConfig(scope.row)"
                  :disabled="scope.row.isSystem"
                >编辑</el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteConfig(scope.row)"
                  :disabled="scope.row.isSystem"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 操作按钮 -->
    <div class="config-actions">
      <el-button type="primary" @click="handleSave" :loading="saving">保存配置</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="info" @click="handleInitDefaults">恢复默认</el-button>
    </div>

    <!-- 添加/编辑自定义配置对话框 -->
    <el-dialog :title="configDialogTitle" v-model="configDialogVisible" width="600px">
      <el-form ref="configFormRef" :model="configForm" :rules="configRules" label-width="100px">
        <el-form-item label="配置键" prop="configKey">
          <el-input v-model="configForm.configKey" placeholder="请输入配置键" :disabled="configForm.id" />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <el-input 
            v-model="configForm.configValue" 
            type="textarea" 
            :rows="3"
            placeholder="请输入配置值" 
          />
        </el-form-item>
        <el-form-item label="配置类型" prop="configType">
          <el-select v-model="configForm.configType" placeholder="请选择配置类型">
            <el-option label="字符串" value="STRING" />
            <el-option label="数字" value="NUMBER" />
            <el-option label="布尔值" value="BOOLEAN" />
            <el-option label="JSON对象" value="JSON" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="configForm.description" placeholder="请输入配置描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitConfigForm">确 定</el-button>
          <el-button @click="configDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getTenantConfigs,
  setTenantConfig,
  batchSetTenantConfigs,
  deleteTenantConfig,
  initTenantDefaultConfigs
} from '@/api/tenant'

// Props
const props = defineProps({
  tenantId: {
    type: String,
    required: true
  }
})

// Emits
const emit = defineEmits(['close'])

// 响应式数据
const activeTab = ref('system')
const saving = ref(false)
const customLoading = ref(false)
const configDialogVisible = ref(false)
const configDialogTitle = ref('')
const customConfigs = ref([])

// 表单引用
const configFormRef = ref()

// 配置数据
const systemConfig = reactive({
  theme: 'default',
  language: 'zh-CN',
  timezone: 'Asia/Shanghai'
})

const featureConfig = reactive({
  fileUpload: true,
  onlineChat: true,
  videoCall: false,
  screenShare: false,
  aiAssistant: true
})

const limitConfig = reactive({
  maxFileSize: 100,
  storageQuotaPerUser: 1000,
  maxConcurrentSessions: 5,
  apiRateLimit: 1000
})

const securityConfig = reactive({
  passwordMinLength: 8,
  passwordComplexity: true,
  sessionTimeout: 30,
  maxLoginAttempts: 5,
  twoFactorAuth: false
})

const notificationConfig = reactive({
  emailEnabled: true,
  smsEnabled: false,
  pushEnabled: true,
  systemAnnouncement: true
})

// 自定义配置表单
const configForm = reactive({
  id: undefined,
  configKey: '',
  configValue: '',
  configType: 'STRING',
  description: ''
})

// 自定义配置表单验证规则
const configRules = reactive({
  configKey: [
    { required: true, message: '配置键不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9._-]*$/, message: '配置键格式不正确', trigger: 'blur' }
  ],
  configValue: [
    { required: true, message: '配置值不能为空', trigger: 'blur' }
  ],
  configType: [
    { required: true, message: '配置类型不能为空', trigger: 'change' }
  ]
})

// 获取租户配置
const getTenantConfigData = async () => {
  try {
    const response = await getTenantConfigs(props.tenantId)
    const configs = response.data

    // 解析配置数据
    configs.forEach(config => {
      const { configKey, configValue, configType } = config
      let value = configValue

      // 根据类型转换值
      if (configType === 'BOOLEAN') {
        value = configValue === 'true'
      } else if (configType === 'NUMBER') {
        value = Number(configValue)
      }

      // 分配到对应的配置对象
      if (configKey.startsWith('system.')) {
        const key = configKey.replace('system.', '')
        if (systemConfig.hasOwnProperty(key)) {
          systemConfig[key] = value
        }
      } else if (configKey.startsWith('feature.')) {
        const key = configKey.replace('feature.', '')
        if (featureConfig.hasOwnProperty(key)) {
          featureConfig[key] = value
        }
      } else if (configKey.startsWith('limit.')) {
        const key = configKey.replace('limit.', '')
        if (limitConfig.hasOwnProperty(key)) {
          limitConfig[key] = value
        }
      } else if (configKey.startsWith('security.')) {
        const key = configKey.replace('security.', '')
        if (securityConfig.hasOwnProperty(key)) {
          securityConfig[key] = value
        }
      } else if (configKey.startsWith('notification.')) {
        const key = configKey.replace('notification.', '')
        if (notificationConfig.hasOwnProperty(key)) {
          notificationConfig[key] = value
        }
      } else {
        // 自定义配置
        customConfigs.value.push(config)
      }
    })
  } catch (error) {
    ElMessage.error('获取租户配置失败')
  }
}

// 保存配置
const handleSave = async () => {
  try {
    saving.value = true

    // 准备配置数据
    const configs = []

    // 系统配置
    Object.keys(systemConfig).forEach(key => {
      configs.push({
        configKey: `system.${key}`,
        configValue: String(systemConfig[key]),
        configType: 'STRING',
        description: `系统配置-${key}`
      })
    })

    // 功能配置
    Object.keys(featureConfig).forEach(key => {
      configs.push({
        configKey: `feature.${key}`,
        configValue: String(featureConfig[key]),
        configType: 'BOOLEAN',
        description: `功能配置-${key}`
      })
    })

    // 限制配置
    Object.keys(limitConfig).forEach(key => {
      configs.push({
        configKey: `limit.${key}`,
        configValue: String(limitConfig[key]),
        configType: 'NUMBER',
        description: `限制配置-${key}`
      })
    })

    // 安全配置
    Object.keys(securityConfig).forEach(key => {
      configs.push({
        configKey: `security.${key}`,
        configValue: String(securityConfig[key]),
        configType: typeof securityConfig[key] === 'boolean' ? 'BOOLEAN' : 'NUMBER',
        description: `安全配置-${key}`
      })
    })

    // 通知配置
    Object.keys(notificationConfig).forEach(key => {
      configs.push({
        configKey: `notification.${key}`,
        configValue: String(notificationConfig[key]),
        configType: 'BOOLEAN',
        description: `通知配置-${key}`
      })
    })

    await batchSetTenantConfigs(props.tenantId, configs)
    ElMessage.success('保存配置成功')
  } catch (error) {
    ElMessage.error('保存配置失败')
  } finally {
    saving.value = false
  }
}

// 重置配置
const handleReset = () => {
  getTenantConfigData()
  ElMessage.info('配置已重置')
}

// 恢复默认配置
const handleInitDefaults = async () => {
  try {
    await ElMessageBox.confirm(
      '确认要恢复默认配置吗？这将覆盖当前所有配置。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await initTenantDefaultConfigs(props.tenantId)
    ElMessage.success('恢复默认配置成功')
    getTenantConfigData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('恢复默认配置失败')
    }
  }
}

// 添加自定义配置
const handleAddConfig = () => {
  resetConfigForm()
  configDialogTitle.value = '添加自定义配置'
  configDialogVisible.value = true
}

// 编辑自定义配置
const handleEditConfig = (row) => {
  Object.assign(configForm, row)
  configDialogTitle.value = '编辑自定义配置'
  configDialogVisible.value = true
}

// 删除自定义配置
const handleDeleteConfig = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确认要删除配置"${row.configKey}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteTenantConfig(props.tenantId, row.configKey)
    ElMessage.success('删除配置成功')
    getTenantConfigData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除配置失败')
    }
  }
}

// 导入配置
const handleImportConfig = () => {
  ElMessage.info('导入配置功能开发中...')
}

// 导出配置
const handleExportConfig = () => {
  ElMessage.info('导出配置功能开发中...')
}

// 提交自定义配置表单
const submitConfigForm = () => {
  configFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        await setTenantConfig(
          props.tenantId,
          configForm.configKey,
          configForm.configValue,
          configForm.configType,
          configForm.description
        )

        ElMessage.success(configForm.id ? '修改配置成功' : '添加配置成功')
        configDialogVisible.value = false
        getTenantConfigData()
      } catch (error) {
        ElMessage.error(configForm.id ? '修改配置失败' : '添加配置失败')
      }
    }
  })
}

// 重置自定义配置表单
const resetConfigForm = () => {
  Object.assign(configForm, {
    id: undefined,
    configKey: '',
    configValue: '',
    configType: 'STRING',
    description: ''
  })
  configFormRef.value?.resetFields()
}

// 获取配置类型标签
const getConfigTypeTag = (type) => {
  const tagMap = {
    'STRING': 'primary',
    'NUMBER': 'success',
    'BOOLEAN': 'warning',
    'JSON': 'info'
  }
  return tagMap[type] || 'info'
}

// 组件挂载时获取数据
onMounted(() => {
  getTenantConfigData()
})
</script>

<style lang="scss" scoped>
.tenant-config {
  .config-section {
    padding: 20px;

    .config-desc {
      margin-left: 10px;
      color: #909399;
      font-size: 12px;
    }

    .config-unit {
      margin-left: 10px;
      color: #606266;
      font-size: 14px;
    }

    .custom-config-header {
      margin-bottom: 20px;

      .el-button {
        margin-right: 10px;
      }
    }
  }

  .config-actions {
    margin-top: 30px;
    padding: 20px;
    text-align: center;
    border-top: 1px solid #ebeef5;

    .el-button {
      margin: 0 10px;
    }
  }

  .dialog-footer {
    text-align: right;

    .el-button {
      margin-left: 10px;
    }
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-switch) {
  .el-switch__label {
    color: #606266;
  }
}

:deep(.el-input-number) {
  .el-input__inner {
    text-align: left;
  }
}
</style>
